﻿using System.Collections.Generic;
using RedirectManager.Interfaces;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Links;

namespace RedirectManager.Providers.Sql
{
    public class Redirect : IRedirect
    {
        public Redirect(bool enabled, string responseTargetId, string requestPath, string sites, int responseStatusCode)
        {
            this.Enabled = enabled;
            this.RequestPath = requestPath;
            this.ResponseStatusCode = responseStatusCode;
            this.ResponseTargetId = responseTargetId;
            this.Sites = sites != null ? sites.Split('|') : null;
        }

        public bool Enabled { get; private set; }

        public string ResponseTargetId { get; private set; }
        
        public int ResponseStatusCode { get; private set; }
        
        public string RequestPath { get; private set; }

        public IEnumerable<string> Sites { get; private set; }

        public string GetTargetUrl(string sitename)
        {
            var item = this.GetTargetItem();
            if (item != null)
            {
                var options = LinkManager.GetDefaultUrlOptions();
                options.AlwaysIncludeServerUrl = true;
                var url = LinkManager.GetItemUrl(item);
                return url;
            }

            return null;
        }
        
        private Item GetTargetItem()
        {
            var db = Sitecore.Context.Database;
            Assert.IsNotNull(db, "Context database");
            return db.Items[this.ResponseTargetId];
        }
    }
}
